<template>
  <el-dialog
    title="批量导入学员"
    :visible.sync="showDialog"
    width="70%"
    @close="closeFn"
  >
    <el-steps :active="active" align-center>
      <el-step title="下载、导入" description="下载模板,导入文件" />
      <el-step title="预览、上传" description="本地预览数据、上传数据" />
    </el-steps>
    <el-col v-if="!isShow" :span="12">
      <el-row type="flex" justify="center" align="middle" style="margin-top: 30px">
        <el-button type="success" size="small" @click="downloadExcel">下载模板</el-button>
        <span style="margin-left: 10px">学生信息模板.xls</span>
      </el-row>
    </el-col>
    <el-col v-if="!isShow" :span="12">
      <el-row type="flex" justify="center" align="middle" style="margin-top: 30px">
        <el-button type="warning" size="small" @click="handleUpload">导入excle</el-button>
        <span v-if="newArr.length" style="margin-left: 10px">{{ fileName }}</span>
        <span v-else style="margin-left: 10px">文件大小不要超过50kb</span>
      </el-row>
    </el-col>
    <el-row slot="footer" type="flex" justify="center" style="margin-top: 50px">
      <span class="dialog-footer">
        <el-button v-if="!isShow" type="primary" @click="nextStepFn">下一步</el-button>
        <el-button v-if="isShow" type="warning" @click="prevStepFn">上一步</el-button>
        <el-button v-if="isShow" type="primary" @click="importData">上传数据</el-button>
        <!-- <el-button type="primary" @click="test">test</el-button> -->
      </span>
    </el-row>
    <el-alert
      v-if="isShow"
      title="请核查数据是否有无，有可删除该条数据！"
      type="warning"
      center
      show-icon
    />
    <!-- 上传文件成功后的列表 -->
    <el-table
      v-if="isShow"
      :data="showArr"
      border
      style="width: 100%"
    >
      <el-table-column
        prop="student_name"
        label="姓名"
        width="100"
        align="center"
      />
      <el-table-column
        prop="student_sex"
        label="性别"
        width="100"
        align="center"
      />
      <el-table-column
        prop="student_phone"
        label="手机号"
        width="140"
        align="center"
      />
      <el-table-column
        prop="class_id"
        label="班级ID"
        width="100"
        align="center"
      />
      <el-table-column
        prop="class_name"
        label="班级名称"
        width="100"
        align="center"
      />
      <el-table-column
        prop="subject_id"
        label="学科ID"
        width="100"
        align="center"
      />
      <el-table-column
        prop="subject_name"
        label="学科名称"
        width="100"
        align="center"
      />
      <el-table-column
        prop="student_state"
        label="账号状态"
        align="center"
      />
      <el-table-column
        fixed="right"
        label="操作"
        width="160"
        align="center"
      >
        <template slot-scope="{$index}">
          <el-button type="danger" icon="el-icon-delete" circle @click="delClass($index)" />
        </template>
      </el-table-column>
    </el-table>
    <input
      ref="excel-upload-input"
      style="display: none"
      type="file"
      accept=".xlsx, .xls"
      @change="handleClick"
    >
  </el-dialog>
</template>

<script>
import { getStudentInfo, importStudentInfo } from '@/api/class'
import XLSX from 'xlsx'
export default {
  name: 'UploadExcel',
  props: {
    page: {
      type: Object,
      required: true,
      default: () => ({ total: 1000 })
    },
    tableData: {
      type: Array,
      required: true,
      default: () => []
    }
  },
  data() {
    return {
      active: 1, // 激活的步骤个数
      isShow: false,
      showDialog: false,
      excelData: {
        header: null,
        results: null
      },
      newArr: [], // 上传数据
      showArr: [], // 展示数据
      fileName: ''
    }
  },
  methods: {
    // 下载模板
    downloadExcel() {
      import('@/vendor/Export2Excel').then(async excel => {
        // 1. 找到所有要导出的员工数据
        const data = await getStudentInfo({ page: 1, size: this.page.total })
        console.log(data)
        // 2. 准备表头数据
        const headers = {
          '姓名': 'student_name',
          '性别': 'student_sex',
          '手机号': 'student_phone',
          '班级ID': 'class_id',
          '班级名称': 'class_name',
          '学科ID': 'subject_id',
          '学科名称': 'subject_name',
          '账号状态': 'student_state'
        }
        excel.export_json_to_excel({
          header: Object.keys(headers), // 常规表头
          // multiHeader: [['姓名', '基本信息', '', '', '', '', '部门']], // 复杂表头
          // merges: ['A1:A2', 'B1:F1', 'G1:G2'], // 合并
          data: this.formatJson(headers, data.data), // 表数据
          filename: '员工信息记录' // 文件名称
        })
      })
    },
    // 整理表格的数据
    formatJson(headers, rows) {
      // 表格需要的表头是 Object.keys(headers)
      // 需要的结构：[['张三', '18868816185'],['里斯', '18868816185'],['王五', '18868816185']]
      // 目前的结构：[{ username:'张三',mobile: 18868816185},{ username:'里斯',mobile: 18868816185},{ username:'王五',mobile: 18868816185}]
      return rows.map(item => {
        // item 是什么==> { username:'张三',mobile: 18868816185}
        // Object.keys(headers) ==> [姓名,手机号,入职日期,....]
        return Object.keys(headers).map(key => {
          // headers[key] 汉字对应的英文
          // if (headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime') {
          //   return formatDate(item[headers[key]]) // 返回格式化之前的时间
          // } else if (headers[key] === 'formOfEmployment') {
          //   var en = employeesConstant.hireType.find(obj => obj.id === item[headers[key]])
          //   return en ? en.value : '未知'
          // }
          return item[headers[key]]
        })
      })
    },
    // async test() {
    //   const data = await getStudentInfo({ page: 1, limit: this.page.total })
    //   console.log(data)
    // }
    // ------------------------
    generateData({ header, results }) {
      this.excelData.header = header
      this.excelData.results = results
      this.success(this.excelData)
    },
    // 点击上传触发文件input
    handleUpload() {
      this.$refs['excel-upload-input'].click()
    },
    handleClick(e) {
      const files = e.target.files
      const rawFile = files[0] // only use files[0]
      if (!this.isExcel(rawFile)) {
        this.$message.error('仅支持上传 .xlsx, .xls, .csv 类型文件')
        return false
      }
      if (!rawFile) return
      this.upload(rawFile)
    },
    upload(rawFile) {
      this.$refs['excel-upload-input'].value = null // fix can't select the same excel
      if (!this.beforeUpload) {
        this.readerData(rawFile)
        return
      }
      const before = this.beforeUpload(rawFile)
      if (before) {
        this.readerData(rawFile)
      }
    },
    readerData(rawFile) {
      this.fileName = rawFile.name
      this.loading = true
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.onload = e => {
          const data = e.target.result
          const workbook = XLSX.read(data, { type: 'array' })
          const firstSheetName = workbook.SheetNames[0]
          const worksheet = workbook.Sheets[firstSheetName]
          const header = this.getHeaderRow(worksheet)
          const results = XLSX.utils.sheet_to_json(worksheet)
          this.generateData({ header, results })
          this.loading = false
          resolve()
        }
        reader.readAsArrayBuffer(rawFile)
      })
    },
    async success({ header, results }) {
      // console.log(header)
      // console.log(results)
      this.newArr = results
      const userRelations = {
        '姓名': 'student_name',
        // '姓名': 'student_name',
        '性别': 'student_sex',
        '手机号': 'student_phone',
        '班级ID': 'class_id',
        '班级名称': 'class_name',
        '学科ID': 'subject_id',
        '学科名称': 'subject_name',
        '账号状态': 'student_state'
      }
      this.showArr = results.map(item => {
        const userInfo = {}
        Object.keys(item).forEach(key => {
          // console.log(key)
          if (userRelations[key] === 'timeOfEntry' || userRelations[key] === 'correctionTime') {
            userInfo[userRelations[key]] = new Date(this.formatDate(item[key], '/')) // 只有这样, 才能入库
            return
          }
          userInfo[userRelations[key]] = item[key]
        })
        return userInfo
      })
      // await importEmployee(newArr)
      // this.$message.success('导入信息成功')
      // this.$router.back()
    },
    getHeaderRow(sheet) {
      const headers = []
      const range = XLSX.utils.decode_range(sheet['!ref'])
      let C
      const R = range.s.r
      /* start in the first row */
      for (C = range.s.c; C <= range.e.c; ++C) { /* walk every column in the range */
        const cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })]
        /* find the cell in the first row */
        let hdr = 'UNKNOWN ' + C // <-- replace with your desired default
        if (cell && cell.t) hdr = XLSX.utils.format_cell(cell)
        headers.push(hdr)
      }
      return headers
    },
    isExcel(file) {
      // console.log(file)
      return /\.(xlsx|xls|csv)$/.test(file.name)
    },
    // 点击下一步事件
    nextStepFn() {
      if (this.newArr.length === 0) return this.$message.warning('请选择文件')
      this.isShow = true
      this.active = 2
    },
    // 删除事件
    delClass($index) {
      // console.log($index)
      this.newArr.splice($index, 1)
      this.showArr.splice($index, 1)
    },
    // 导入数据
    async importData() {
      if (this.newArr.length === 0 && this.showArr.length === 0) return this.$message.warning('请确保有文件数据再上传')
      await importStudentInfo({ list: this.newArr })
      this.$message.success('导入学生信息成功!')
      this.showDialog = false
      this.$parent.$parent.getStudentInfo()
      this.newArr = []
      this.showArr = []
      this.isShow = false
      this.active = 1
    },
    // 上一步事件
    prevStepFn() {
      this.isShow = false
      this.active = 1
    },
    // 关闭事件
    closeFn() {
      this.newArr = []
      this.showArr = []
      this.isShow = false
      this.active = 1
    }
  }
}
</script>

<style>

</style>
